package db_main

import (
	"errors"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/const"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
	pb "longmen/server/pkg/protobuf"
	"time"

	"gorm.io/gorm"
	"longmen/server/pkg/common/api_models"
)

func GetGiftLogSumsParam(param map[string]interface{}, selectCol, groupBy, order string, page, size int) ([]*api_models.GiftLog, error) {
	o := make([]*api_models.GiftLog, 0)
	table := global.Live().Model(&models_main.GiftLog{})
	table.Select(selectCol)
	mysql.Condition(table, param, groupBy, order, page, size)
	err := table.Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	return o, err
}

//目前只是统计diamond
func GetContributeRank(r *pb.ContributeRankReq) ([]*pb.ContributeRank, error) {
	var start, end time.Time
	//日榜单
	if r.Type == 0 {
		start, end = time2.GetTodayDateTime()
	} else {
		//周榜单
		start, end = time2.GetWeekStartAndEndWithTimeStamp()
	}
	contributes, err := GetGiftLogSumsParam(map[string]interface{}{
		"anchorid":    r.Anchorid,
		"spend_type":  _const.CoinDiamond,
		"create_time": map[string]interface{}{">": start, "<": end},
	}, "id,uid,anchorid,liveid,(sum(spend)) as intimacy", "uid", "intimacy desc", 0, 5)
	if err != nil {
		return nil, err
	}
	tmpIds := make([]int, 0)
	for i := range contributes {
		tmpIds = append(tmpIds, contributes[i].Uid)
	}
	userMap, err := GetPartUsersParam(map[string]interface{}{"id": map[string]interface{}{"in": tmpIds}}, "", 0, 0)
	if err != nil {
		return nil, err
	}

	resp := make([]*pb.ContributeRank, 0)

	for _, v := range contributes {
		getContributeRankResp := &pb.User{}
		for _, u := range userMap {
			if u.Id == v.Uid {
				getContributeRankResp.Uid = int32(v.Uid)
				getContributeRankResp.NickName = u.NickName
				getContributeRankResp.Avatar = u.Avatar
				break
			}
		}

		resp = append(resp, &pb.ContributeRank{
			Id:       int32(v.Id),
			Uid:      int32(v.Uid),
			Anchorid: int32(v.Anchorid),
			Liveid:   v.Liveid,
			Intimacy: int32(v.Intimacy / 10), // 贡献除以10显示
			User:     getContributeRankResp,
		})

	}
	return resp, nil
}

func GetSendGiftSum(param map[string]interface{}, column string) (int64, error) {
	o := &mysql.Total{}
	table := global.Live().Model(&models_main.GiftLog{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Select(fmt.Sprintf("sum(%s) as s", column)).Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	return o.S, err
}
